using System.Runtime.InteropServices;
using System.Text;

namespace CSharpWebService.Services
{
    public class HttpService
    {
        // 回调委托定义
        [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
        public delegate void HttpCallback(string response, int errorCode);

        // DLL导入声明
        [DllImport("libCRequestLib.dylib", CallingConvention = CallingConvention.Cdecl)]
        private static extern void http_get_async(string url, HttpCallback callback);

        // 异步GET请求
        public async Task<string> GetAsync(string url)
        {
            var completionSource = new TaskCompletionSource<string>();
            
            HttpCallback callback = (response, errorCode) =>
            {
                if (errorCode == 0 && !string.IsNullOrEmpty(response))
                {
                    completionSource.SetResult(response);
                }
                else
                {
                    completionSource.SetException(new Exception($"HTTP请求失败，错误码: {errorCode}"));
                }
            };

            try
            {
                http_get_async(url, callback);
                return await completionSource.Task;
            }
            catch (Exception ex)
            {
                throw new Exception($"调用C语言库失败: {ex.Message}", ex);
            }
        }

        // 同步GET请求（包装异步方法）
        public string Get(string url)
        {
            return GetAsync(url).GetAwaiter().GetResult();
        }
    }
}
